import logging
from datetime import datetime, timedelta
from types import SimpleNamespace

from fastapi import APIRouter, Depends

from app.models.gps_model import GpsModel
from app.services.gps_service import gps_service, GpsService;
from app.services.pljs_service import FatigueAnalyzer
from app.utils.response_result import resp_200, resp_500

router = APIRouter()


@router.post("/query", summary="疲劳驾驶查询接口")
def query_ck(gpsModel: GpsModel):
    simple_date_format = "%Y-%m-%d %H:%M:%S"
    try:
        now = datetime.now()
        if not gpsModel.end_time:
            gpsModel.end_time = now.strftime(simple_date_format)
        if not gpsModel.start_time:
            twenty_four_hours_ago = (now - timedelta(hours=24)).strftime(simple_date_format)
            gpsModel.start_time = twenty_four_hours_ago
        logging.info(f"本次查询参数{str(gpsModel)}")
        track_list = gps_service.searchClickHouse(gpsModel)
        if not track_list:
            return resp_200(data=dict(), message=f"{gpsModel.vehicle_no}没有轨迹信息")
        IllegalDetail: FatigueAnalyzer = FatigueAnalyzer(vehicle_name=gpsModel.vehicle_no, track_list=track_list)
        data = IllegalDetail.call()
        return resp_200(data=data)
    except Exception as e:
        logging.error(f"数据查询错误:{str(e)}")
        return resp_500(message=f"数据查询错误:{str(e)}")


def query_gps(body: dict):
    gpsModel: GpsModel = SimpleNamespace(**body)
    return query_ck(gpsModel)
